import React, { useState } from "react";
import { DropResult, DragDropContext, Droppable } from "react-beautiful-dnd";
import { Column } from "../components/Column";
import { PanelsContainer } from "../components/lib";
import { initialData } from "../state/initial-data";
import { reOrder } from "../utils";

export const DragDemo = () => {
  const [columns, setColumns] = useState(initialData.columns);
  const [tasks, setTasks] = useState(initialData.tasks);
  const onDragEnd = (result: DropResult) => {
    const { type } = result;
    if (type === "columns") {
      if (result.destination) {
        reOrder(columns, result.source.index, result.destination.index);
        setColumns(() => [...columns]);
      }
    } else {
      // Task
      // 同一个Column下
      if (result.source.droppableId === result.destination?.droppableId) {
        const index = columns.findIndex(
          (col) => col.id === result.source.droppableId
        );
        if (index >= 0 && result.destination) {
          const tasks = columns[index].taskIds;
          reOrder(tasks, result.source.index, result.destination.index);
          columns[index].taskIds = tasks;
          setColumns(() => [...columns]);
        }
      } else {
        // 两个column之间的拖拽
        const index = columns.findIndex(
          (col) => col.id === result.source.droppableId
        );
        const destIndex = columns.findIndex(
          (col) => col.id === result.destination?.droppableId
        );
        if (~index && ~destIndex) {
          const sourceTasks = columns[index].taskIds;
          const dragTask = sourceTasks[result.source.index];
          sourceTasks.splice(result.source.index, 1);
          const destinationTasks = columns[destIndex].taskIds;
          destinationTasks.splice(result.destination!.index, 0, dragTask);
          setColumns(() => [...columns]);
        }
      }
    }
  };
  return (
    <>
      <DragDropContext onDragEnd={onDragEnd}>
        <Droppable
          droppableId={"columns"}
          direction={"horizontal"}
          type="columns"
        >
          {(provided) => {
            return (
              <PanelsContainer
                ref={provided.innerRef}
                {...provided.droppableProps}
              >
                {columns.map((col, index) => {
                  const relatedTasks = col.taskIds.map(
                    (id) =>
                      tasks.find((task) => task.id === id) || {
                        id: "",
                        content: "",
                      }
                  );
                  return (
                    <Column
                      key={col.id}
                      column={col}
                      tasks={relatedTasks}
                      index={index}
                    />
                  );
                })}
                {provided.placeholder}
              </PanelsContainer>
            );
          }}
        </Droppable>
      </DragDropContext>
    </>
  );
};
